package com.cloudpark.controller;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cloudpark.common.util.*;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudpark.common.mqtt.MqttDTO;
import com.cloudpark.common.mqtt.QueryCardDTO;
import com.cloudpark.common.mqtt.QueryCardResultDTO;
import com.cloudpark.common.mqtt.QueryRechargeOrderDTO;
import com.cloudpark.common.mqtt.QueryRechargeOrderResultDTO;
import com.cloudpark.common.mqtt.SendCardRechargeDTO;
import com.cloudpark.common.mqtt.SendPayFeeDTO;
import com.cloudpark.common.util.wechat.MenuHandler;
import com.cloudpark.common.util.wechat.WeChatPayUtil;
import com.cloudpark.model.entity.CardOrder;
import com.cloudpark.model.entity.CardOrderTemp;
import com.cloudpark.model.entity.Estate;
import com.cloudpark.model.entity.EstateWechat;
import com.cloudpark.model.entity.MqttMessage;
import com.cloudpark.model.entity.Park;
import com.cloudpark.model.entity.ParkOrder;
import com.cloudpark.model.entity.ParkOrderTemp;
import com.cloudpark.model.entity.User;
import com.cloudpark.model.vo.Card;
import com.cloudpark.model.vo.CardOrderVo;
import com.cloudpark.model.vo.PlateVo;
import com.cloudpark.mqtt.MQTTPub;
import com.cloudpark.service.EstateService;
import com.cloudpark.service.MqttMessageService;
import com.cloudpark.service.OrderService;
import com.cloudpark.service.ParkService;
import com.cloudpark.service.PlateService;
import com.cloudpark.service.UserService;

@Controller
@RequestMapping("/api")
public class ApiController {

	private final Logger log = LoggerFactory.getLogger(ApiController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private PlateService plateService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private EstateService estateService;
	@Autowired
	private ParkService parkService;
	@Autowired
	private MqttMessageService mqttMessageService;

	/**
	 * 自定义菜单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/customMenu", method = RequestMethod.POST)
	@ResponseBody
	public String customMenu(HttpServletRequest request,
			HttpServletResponse response) {
		String result = "";
		String action = request.getParameter("action");
		if (ObjectUtil.isBlank(action)) {
			result = MessageUtil.error("操作类型不能为空");
		} else {
			result = MenuHandler.customMenu(action);
		}
		return result;
	}

	/**
	 * 查询车牌列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/queryPlateList", method = RequestMethod.POST)
	@ResponseBody
	public String queryPlateList(HttpServletRequest request,
			HttpServletResponse response) {
		String result = "";
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			String uid = request.getParameter("uid");
			List<PlateVo> list = plateService.queryPlateList(Long.valueOf(uid));
			map.put("code", Constants.OK);
			if (ObjectUtil.isNotBlank(list)) {
				map.put("data", list);
			} else {
				list = new ArrayList<PlateVo>();
				map.put("data", list);
			}
			result = JSON.toJSONString(map);
		} catch (Exception e) {
			log.error("query plate list error", e);
			result = MessageUtil.error("服务器忙!");
		}
		return result;
	}

	@RequestMapping(value = "/bindPlate", method = RequestMethod.POST)
	@ResponseBody
	public String bindPlate(HttpServletRequest request,
			HttpServletResponse response) {
		String result = "";
		try {
			String uid = request.getParameter("uid");
			String plateNumber = request.getParameter("plateNumber");
			if (ObjectUtil.isBlank(plateNumber)) {
				result = MessageUtil.error("车牌号不能为空!");
				return result;
			} else {
				boolean isBind = plateService.savePlate(plateNumber,
						Long.valueOf(uid));
				if (isBind) {
					result = MessageUtil.error("该车牌号已经绑定过了,请确认!");
				} else {
					result = MessageUtil.success();
				}
			}
		} catch (Exception e) {
			log.error("bind plate error", e);
			result = MessageUtil.error("服务器忙!");
		}
		return result;
	}

	@RequestMapping(value = "/unbindPlate", method = RequestMethod.POST)
	@ResponseBody
	public String unbindPlate(HttpServletRequest request,
			HttpServletResponse response) {
		String result = "";
		try {
			String uid = request.getParameter("uid");
			String pid = request.getParameter("pid");
			plateService.deleteUserPlate(Long.valueOf(pid), Long.valueOf(uid));
			result = MessageUtil.success();
		} catch (Exception e) {
			log.error("unbind plate error", e);
			result = MessageUtil.error("服务器忙!");
		}
		return result;
	}
	
	/**
	 * 查询月卡列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/queryCardList", method = RequestMethod.POST)
	@ResponseBody
	public String queryCardList(HttpServletRequest request,
			HttpServletResponse response) {
		String result = "";
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			String uid = request.getParameter("uid");
			String ecode = request.getParameter("ecode");
			Estate estate = estateService.queryEstateByCode(ecode);
			if (null == estate) {
				result = MessageUtil.error("配置信息有误,请确认!");
			} else {
				List<Park> parks = parkService.queryParkByEstateId(estate.getId());
				List<PlateVo> plateVos = plateService.queryPlateList(Long.valueOf(uid));
				if (ObjectUtil.isBlank(plateVos)) {
					result = MessageUtil.zero();
				} else if (ObjectUtil.isBlank(parks)) {
					result = MessageUtil.zero();
				} else {
					StringBuilder plateNumber = new StringBuilder();
					StringBuilder parkCode = new StringBuilder();
					int i = 0;
					for (PlateVo plateVo : plateVos) {
						if (i==0) {
							plateNumber.append(plateVo.getPlateNumber());
						} else {
							plateNumber.append(",").append(plateVo.getPlateNumber());
						}
						i++;
					}
					int j = 0;
					for (Park park : parks) {
						if (j==0) {
							parkCode.append(park.getParkCode());
						} else {
							parkCode.append(",").append(park.getParkCode());
						}
						j++;
					}
					
					// send mqtt message
		    		MqttDTO<QueryCardDTO> mqttDTO = new MqttDTO<QueryCardDTO>();
		    		List<QueryCardDTO> dataItems = new ArrayList<QueryCardDTO>();
		    		QueryCardDTO queryCardDTO = new QueryCardDTO();
		    		queryCardDTO.setPlateNumber(plateNumber.toString());
		    		queryCardDTO.setParkCode(parkCode.toString());
	    			dataItems.add(queryCardDTO);
		    		mqttDTO.setCode(Constants.OK);
		    		mqttDTO.setServiceId(Constants.PAY_QUERY_MONTH_CARD);
		    		mqttDTO.setUuid(UuidUtil.getUUID());
		    		mqttDTO.setDataItems(dataItems);
		    		String sendMessage = JSON.toJSONString(mqttDTO);
		    		log.info("query cards by params = {}", sendMessage);
		    		
		    		MqttMessage mqttMessage = mqttMessageService.save(mqttDTO.getUuid(), sendMessage);
		    		boolean success = MQTTPub.getSingleton().publish(sendMessage);
		    		if (success) {
		    			mqttMessage.setSendStatus(Constants.MQTT_STATUS_SENDED);
		    			mqttMessageService.update(mqttMessage);
		    		};
					
		    		// query mqtt result from db
		    		List<Card> cards = new ArrayList<Card>();
		    		mqttMessage = mqttMessageService.queryById(mqttMessage.getId());
		    		if (null != mqttMessage.getReceiveStatus() && mqttMessage.getReceiveStatus().intValue() == Constants.MQTT_STATUS_RECEIVED) {
		    			cards = doHandlerCards(mqttMessage);
		    		} else {
		    			try {
		    				long sleepTimes = 2000l;
		    				log.info(Constants.PAY_QUERY_MONTH_CARD + " waiting for mqtt callback result, sleeping "+sleepTimes+" ms");
							Thread.sleep(sleepTimes);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
		    			mqttMessage = mqttMessageService.queryById(mqttMessage.getId());
		    			if (null != mqttMessage.getReceiveStatus() && mqttMessage.getReceiveStatus().intValue() == Constants.MQTT_STATUS_RECEIVED) {
		    				cards = doHandlerCards(mqttMessage);
		        		}
		    		}
					map.put("code", Constants.OK);
					map.put("data", cards);
					result = JSON.toJSONString(map);
				}
			}
		} catch (Exception e) {
			log.error("query card list error", e);
			result = MessageUtil.error("服务器忙!");
		}
		return result;
	}
	
	/**
	 * 月卡信息处理
	 * @param mqttMessage
	 * @return
	 */
	private List<Card> doHandlerCards(MqttMessage mqttMessage) {
		List<Card> list = new ArrayList<Card>();
		if (ObjectUtil.isNotBlank(mqttMessage.getReceiveMessage())) {
			JSONObject jsonObject = JSON.parseObject(mqttMessage.getReceiveMessage());
	        String dataItems = jsonObject.getString("dataItems");
	        List<QueryCardResultDTO> queryCardResultDTOs = JSON.parseArray(dataItems, QueryCardResultDTO.class);
	        for (QueryCardResultDTO queryCardResultDTO : queryCardResultDTOs) {
	        	Card card = new Card();
	        	card.setPlateNumber(queryCardResultDTO.getPlateNumber());
	        	card.setParkCode(queryCardResultDTO.getParkCode());
	        	card.setPrice(queryCardResultDTO.getPrice());
	        	card.setDeadlineDate(queryCardResultDTO.getDeadlineDate());
	        	card.setStatus(queryCardResultDTO.getStatus());
	        	Park park = parkService.queryByParkCode(card.getParkCode());
	        	card.setParkName(park.getName());
	        	list.add(card);
	        }
		}
		return list;
	}
	
	/**
	 * 查询月卡订单列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/queryCardOrderList", method = RequestMethod.POST)
	@ResponseBody
	public String queryCardOrderList(HttpServletRequest request,
			HttpServletResponse response) {
		String result = "";
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			String uid = request.getParameter("uid");
			String ecode = request.getParameter("ecode");
			String plateNumber = request.getParameter("plateNumber");
			String parkCode = request.getParameter("parkCode");
					
			// send mqtt message
    		MqttDTO<QueryRechargeOrderDTO> mqttDTO = new MqttDTO<QueryRechargeOrderDTO>();
    		List<QueryRechargeOrderDTO> dataItems = new ArrayList<QueryRechargeOrderDTO>();
    		QueryRechargeOrderDTO queryRechargeOrderDTO = new QueryRechargeOrderDTO();
    		queryRechargeOrderDTO.setPlateNumber(plateNumber);
    		queryRechargeOrderDTO.setParkCode(parkCode);
			dataItems.add(queryRechargeOrderDTO);
    		mqttDTO.setCode(Constants.OK);
    		mqttDTO.setServiceId(Constants.PAY_QUERY_MONTH_ORDER_LIST);
    		mqttDTO.setUuid(UuidUtil.getUUID());
    		mqttDTO.setDataItems(dataItems);
    		String sendMessage = JSON.toJSONString(mqttDTO);
    		log.info("query card orders by params = {}", sendMessage);
    		
    		MqttMessage mqttMessage = mqttMessageService.save(mqttDTO.getUuid(), sendMessage);
    		boolean success = MQTTPub.getSingleton().publish(sendMessage);
    		if (success) {
    			mqttMessage.setSendStatus(Constants.MQTT_STATUS_SENDED);
    			mqttMessageService.update(mqttMessage);
    		};
			
    		// query mqtt result from db
    		List<CardOrderVo> cardOrders = new ArrayList<CardOrderVo>();
    		mqttMessage = mqttMessageService.queryById(mqttMessage.getId());
    		if (null != mqttMessage.getReceiveStatus() && mqttMessage.getReceiveStatus().intValue() == Constants.MQTT_STATUS_RECEIVED) {
    			cardOrders = doHandlerCardOrders(mqttMessage);
    		} else {
    			try {
    				long sleepTimes = 2000l;
    				log.info(Constants.PAY_QUERY_MONTH_ORDER_LIST + " waiting for mqtt callback result, sleeping "+sleepTimes+" ms");
					Thread.sleep(sleepTimes);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
    			mqttMessage = mqttMessageService.queryById(mqttMessage.getId());
    			if (null != mqttMessage.getReceiveStatus() && mqttMessage.getReceiveStatus().intValue() == Constants.MQTT_STATUS_RECEIVED) {
    				cardOrders = doHandlerCardOrders(mqttMessage);
        		}
    		}
			map.put("code", Constants.OK);
			map.put("data", cardOrders);
			result = JSON.toJSONString(map);
		} catch (Exception e) {
			log.error("query card order list error", e);
			result = MessageUtil.error("服务器忙!");
		}
		return result;
	}

	private List<CardOrderVo> doHandlerCardOrders(MqttMessage mqttMessage) {
		List<CardOrderVo> list = new ArrayList<CardOrderVo>();
		if (ObjectUtil.isNotBlank(mqttMessage.getReceiveMessage())) {
			JSONObject jsonObject = JSON.parseObject(mqttMessage.getReceiveMessage());
	        String dataItems = jsonObject.getString("dataItems");
	        List<QueryRechargeOrderResultDTO> queryRechargeOrderResultDTOs = JSON.parseArray(dataItems, QueryRechargeOrderResultDTO.class);
	        for (QueryRechargeOrderResultDTO queryRechargeOrderResultDTO : queryRechargeOrderResultDTOs) {
	        	CardOrderVo cardOrderVo = new CardOrderVo();
	        	cardOrderVo.setPlateNumber(queryRechargeOrderResultDTO.getPlateNumber());
	        	cardOrderVo.setParkCode(queryRechargeOrderResultDTO.getParkCode());
	        	cardOrderVo.setRechargeAmount(queryRechargeOrderResultDTO.getRechargeAmount());
	        	cardOrderVo.setStartDate(queryRechargeOrderResultDTO.getStartDate());
	        	cardOrderVo.setEndDate(queryRechargeOrderResultDTO.getEndDate());
	        	cardOrderVo.setPayType(queryRechargeOrderResultDTO.getPayType());
	        	Park park = parkService.queryByParkCode(cardOrderVo.getParkCode());
	        	cardOrderVo.setParkName(park.getName());
	        	list.add(cardOrderVo);
	        }
		}
		return list;
	}

	/**
	 * 创建月卡临时订单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/createCardOrderTemp", method = RequestMethod.POST)
	@ResponseBody
	public String createCardOrderTemp(HttpServletRequest request,
			HttpServletResponse response) {
		String result = "";
		try {
			String plateNumber = request.getParameter("plateNumber");
			String parkCode = request.getParameter("parkCode");
			String rechargeNum = request.getParameter("rechargeNum");
			String price = request.getParameter("price");
			log.info("createCardOrderTemp receive params: plateNumber = {}, parkCode = {}, rechargeNum = {}, price = {}", plateNumber , parkCode, rechargeNum, price);
			CardOrderTemp cardOrderTemp = new CardOrderTemp();
			cardOrderTemp.setOrderNo(UuidUtil.getYKOrderNo());
			cardOrderTemp.setRechargeAmount(ArithHelper.mul(Double.valueOf(price), Double.valueOf(rechargeNum)));
			cardOrderTemp.setPayType(Constants.PAY_BY_WECHAT);
			cardOrderTemp.setPayChannel(Constants.PAY_CHANNEL_1);
			cardOrderTemp.setParkCode(parkCode);
			cardOrderTemp.setPlateNumber(plateNumber);
			cardOrderTemp.setRechargeNum(Integer.valueOf(rechargeNum));
			cardOrderTemp.setCreatedTime(new Date());
			orderService.saveCardOrderTemp(cardOrderTemp);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", Constants.OK);
			map.put("orderNo", cardOrderTemp.getOrderNo());
			result = JSON.toJSONString(map);
			log.info("createCardOrderTemp send result = {}", result);
		} catch (Exception e) {
			log.error("create card order temp error", e);
			result = MessageUtil.error("服务器忙!");
		}
		return result;
	}
	
	/**
	 * 向微信服务端下单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/initWeixinPay", method = RequestMethod.POST)
	@ResponseBody
	public String initWeixinPay(HttpServletRequest request,
			HttpServletResponse response) {
		String result = "";
		try {
			String dynamicURL = request.getParameter("dynamicURL");
			String uid = request.getParameter("uid");
			String ecode = request.getParameter("ecode");
			String orderNo = request.getParameter("orderNo");
			String body = request.getParameter("body");
			log.info("initWeixinPay recevie params: dynamicURL = {}, uid = {}, ecode = {}, orderNo = {}, body = {}",
					dynamicURL, uid, ecode, orderNo, body);
			String totalFee = "";   // 金额从后台获取,安全
			if (orderNo.startsWith(Constants.ORDER_CATEGORY_TC)) {
				ParkOrderTemp orderTemp = orderService.queryParkOrderTempByOrderNo(orderNo);
				totalFee = String.valueOf(orderTemp.getPaidFee());
			} else if (orderNo.startsWith(Constants.ORDER_CATEGORY_YK)) {
				CardOrderTemp cardOrderTemp = orderService.queryCardOrderTempByOrderNo(orderNo);
				totalFee = String.valueOf(cardOrderTemp.getRechargeAmount());
			}
			User user = userService.findUserById(Long.valueOf(uid));
			Estate estate = estateService.queryEstateByCode(ecode);
			EstateWechat estateWechat = estateService.queryEstateWechatByEstateId(estate.getId());
			String spbill_create_ip = request.getRemoteAddr();
//			String body = "停车订单";
			String attach = orderNo;
			String notify_url = Constants.baseUrl + "api/payNotify";
			result = WeChatPayUtil.initWeixinPay(estateWechat.getAppId(),
					estateWechat.getAppSecret(), estateWechat.getKeySecret(),
					estateWechat.getMchId(), user.getOpenId(), totalFee,
					spbill_create_ip, body, orderNo, attach, notify_url,
					dynamicURL);
			log.info("initWeixinPay send result = {}", result);
		} catch (Exception e) {
			log.error("init weixin pay error", e);
			result = MessageUtil.error("服务器忙!");
		}
		return result;
	}

	/**
	 * 订单支付成功通知
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/paySuccess", method = RequestMethod.POST)
	@ResponseBody
	public String paySuccess(HttpServletRequest request,
			HttpServletResponse response) {
		String result = "";
		try {
			String orderNo = request.getParameter("orderNo");
			Long orderId = orderService.syncOrderFromTemp(orderNo, null);
			
			if (orderNo.startsWith(Constants.ORDER_CATEGORY_TC)) {
				
				notifyTc(orderId);
				
			} else if (orderNo.startsWith(Constants.ORDER_CATEGORY_YK)) {
				
				notifyYk(orderId);
				
			}
			
			log.info("paySuccess sync orderId=" + orderId);
			result = MessageUtil.success();
		} catch (Exception e) {
			log.error("pay sync info error", e);
			result = MessageUtil.error("服务器忙!");
		}
		return result;
	}

	/**
	 * 微信异步回调通知
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/payNotify", method = RequestMethod.POST)
	public void payNotify(HttpServletRequest request,
			HttpServletResponse response) {
		log.info("payNotify message start ..... ");
//		response.setContentType("text/xml");  
		Map<String,String> returnData = new HashMap<String, String>();
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
			String line;
			String param = "";
			while ((line = in.readLine()) != null) {
				param += line;
			}
			log.info("payNotify message msg=" + param);
			Document document = DocumentHelper.parseText(param);
			log.info("payNotify message document:" + document.toString());
			Element root = document.getRootElement();
			String return_code = root.element("return_code").getText();
			if (return_code.equals("SUCCESS") || return_code.indexOf("SUCESS") > -1) {
				String result_code = root.element("result_code").getText();
				if (result_code.equals("SUCCESS") || return_code.indexOf("SUCESS") > -1) {
					String out_trade_no = root.element("out_trade_no").getText();
					String time_end = root.element("time_end").getText();
//					String attach = root.element("attach").getText();
					if (ObjectUtil.isNotBlank(time_end)) {
						if (ObjectUtil.isNotBlank(out_trade_no)) {
							Long orderId = orderService.syncOrderFromTemp(out_trade_no, time_end);
							log.info("payNotify sync orderId=" + orderId);
							if (out_trade_no.startsWith(Constants.ORDER_CATEGORY_TC)) {
								
								notifyTc(orderId);
								
							} else if (out_trade_no.startsWith(Constants.ORDER_CATEGORY_YK)) {
								
								notifyYk(orderId);
								
							}
							returnData.put("return_code", "SUCCESS");
							returnData.put("return_msg", "OK");
							String resultXml = CommonUtil.maptoxml(returnData);
							log.info("return to weixin server msg = {}", resultXml);
					        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
					        out.write(resultXml.getBytes());
					        out.flush();
					        out.close();
						} else {
							log.info("payNotify message : out_trade_no is empty ");
						}
					} else {
						log.info("payNotify message : time_end is empty");
					}
				} else {
					log.error("payNotify message error : " + root.element("err_code_des").getText());
				}
			} else {
				log.error("payNotify message error : " + root.element("return_msg").getText());
			}
		} catch (Exception e) {
			log.error("payNotify by wechat error", e);
		}
//		returnData.put("return_code", "FAIL");
//		returnData.put("return_msg", "error");
//		String resultXml = CommonUtil.maptoxml(returnData);
//		log.info("return to weixin server msg = {}", resultXml);
//		return resultXml;
	}
	
	/**
	 * 月卡订单处理
	 * @param orderId
	 */
	private void notifyYk(Long orderId) {
		CardOrder cardOrder = orderService.queryCardOrderById(orderId);
		// send mqtt message
		MqttDTO<SendCardRechargeDTO> mqttDTO = new MqttDTO<SendCardRechargeDTO>();
		List<SendCardRechargeDTO> dataItems = new ArrayList<SendCardRechargeDTO>();
		SendCardRechargeDTO sendCardRechargeDTO = new SendCardRechargeDTO();
		sendCardRechargeDTO.setPlateNumber(cardOrder.getPlateNumber());
		sendCardRechargeDTO.setRechargeAmount(cardOrder.getRechargeAmount());
		sendCardRechargeDTO.setRechargeTime(DateUtils.toString(cardOrder.getRechargeTime(), DateUtils.YMDHMS));
		sendCardRechargeDTO.setRechargeNum(cardOrder.getRechargeNum());
		sendCardRechargeDTO.setParkCode(cardOrder.getParkCode());
		sendCardRechargeDTO.setPayType(cardOrder.getPayType());
		sendCardRechargeDTO.setOrderNo(cardOrder.getOrderNo());
		dataItems.add(sendCardRechargeDTO);
		mqttDTO.setCode(Constants.OK);
		mqttDTO.setServiceId(Constants.PAY_MONTH_CARD_ORDER);
		mqttDTO.setUuid(UuidUtil.getUUID());
		mqttDTO.setDataItems(dataItems);
		String sendMessage = JSON.toJSONString(mqttDTO);
		
		MqttMessage mqttMessage = new MqttMessage();
		mqttMessage.setUuid(mqttDTO.getUuid());
		mqttMessage.setSponsor(Constants.MQTT_SPONSOR_CLOUDPARK);
		mqttMessage.setSendMessage(sendMessage);
		mqttMessage.setSendStatus(Constants.MQTT_STATUS_SENDIING);
		mqttMessage.setSendTime(new Date());
		mqttMessage.setCreatedTime(new Date());
		mqttMessageService.save(mqttMessage);
		boolean success = MQTTPub.getSingleton().publish(sendMessage);
		if (success) {
			mqttMessage.setSendStatus(Constants.MQTT_STATUS_SENDED);
			mqttMessageService.update(mqttMessage);
		}
		
	}

	/**
	 * 停车订单处理
	 * @param orderId
	 */
	private void notifyTc(Long orderId) {
		ParkOrder order = orderService.queryParkOrderById(orderId);
		// send mqtt message
		MqttDTO<SendPayFeeDTO> mqttDTO = new MqttDTO<SendPayFeeDTO>();
		List<SendPayFeeDTO> dataItems = new ArrayList<SendPayFeeDTO>();
		SendPayFeeDTO sendPayFeeDTO = new SendPayFeeDTO();
		sendPayFeeDTO.setPlateNumber(order.getPlateNumber());
		sendPayFeeDTO.setPaidFee(order.getPaidFee());
		sendPayFeeDTO.setPayType(order.getPayType());
		sendPayFeeDTO.setPayChannel(order.getPayChannel());
		if (Constants.MQTT_TEST_ENV) {
			sendPayFeeDTO.setPayTime(DateUtils.toString(new Date(), DateUtils.YMDHMS));
		} else {
			sendPayFeeDTO.setPayTime(null == order.getPayTime() ? DateUtils.toString(new Date(), DateUtils.YMDHMS) : DateUtils.toString(order.getPayTime(), DateUtils.YMDHMS));
		}
		sendPayFeeDTO.setParkCode(order.getParkCode());
		sendPayFeeDTO.setOrderNo(order.getOrderNo());
		dataItems.add(sendPayFeeDTO);
		mqttDTO.setCode(Constants.OK);
		mqttDTO.setServiceId(Constants.PAY_PARKING_FEE_ORDER);
		mqttDTO.setUuid(UuidUtil.getUUID());
		mqttDTO.setDataItems(dataItems);
		String sendMessage = JSON.toJSONString(mqttDTO);
		
		MqttMessage mqttMessage = new MqttMessage();
		mqttMessage.setUuid(mqttDTO.getUuid());
		mqttMessage.setSponsor(Constants.MQTT_SPONSOR_CLOUDPARK);
		mqttMessage.setSendMessage(sendMessage);
		mqttMessage.setSendStatus(Constants.MQTT_STATUS_SENDIING);
		mqttMessage.setSendTime(new Date());
		mqttMessage.setCreatedTime(new Date());
		mqttMessageService.save(mqttMessage);
		boolean success = MQTTPub.getSingleton().publish(sendMessage);
		if (success) {
			mqttMessage.setSendStatus(Constants.MQTT_STATUS_SENDED);
			mqttMessageService.update(mqttMessage);
		}
	}

	public static void main(String[] args) {
//		MqttDTO<SendPayFeeDTO> mqttDTO = new MqttDTO<SendPayFeeDTO>();
//		List<SendPayFeeDTO> dataItems = new ArrayList<SendPayFeeDTO>();
//		SendPayFeeDTO sendPayFeeDTO = new SendPayFeeDTO();
//		sendPayFeeDTO.setPlateNumber("粤B12345");
//		sendPayFeeDTO.setPaidFee(1.09);
//		sendPayFeeDTO.setPayType(1);
//		sendPayFeeDTO.setPayTime("2017-09-17 00:21:09");
//		sendPayFeeDTO.setParkCode("tdzntest");
//		sendPayFeeDTO.setOrderNo("TC2017091720524614501");
//		dataItems.add(sendPayFeeDTO);
//		mqttDTO.setCode(Constants.OK);
//		mqttDTO.setServiceId(Constants.PAY_PARKING_FEE_ORDER);
//		mqttDTO.setUuid(UuidUtil.getUUID());
//		mqttDTO.setDataItems(dataItems);
//		String sendMessage = JSON.toJSONString(mqttDTO);
//		System.out.println(sendMessage);
//		
//		MqttDTO<SendPayFeeResultDTO> mqttDTO2 = new MqttDTO<SendPayFeeResultDTO>();
//		List<SendPayFeeResultDTO> list = new ArrayList<SendPayFeeResultDTO>();
//		SendPayFeeResultDTO resultSendPayFeeDTO = new SendPayFeeResultDTO();
//		resultSendPayFeeDTO.setOrderNo("TC2017091720524614501");
//		list.add(resultSendPayFeeDTO);
//		mqttDTO2.setCode(Constants.OK);
//		mqttDTO2.setServiceId(Constants.PAY_PARKING_FEE_ORDER);
//		mqttDTO2.setUuid(UuidUtil.getUUID());
//		mqttDTO2.setDataItems(list);
//		System.out.println(JSON.toJSONString(mqttDTO2));
		
		
//		MqttDTO<SyncCardDTO> mqttDTO = new MqttDTO<SyncCardDTO>();
//		List<SyncCardDTO> dataItems = new ArrayList<SyncCardDTO>();
//		SyncCardDTO syncCardDTO = new SyncCardDTO();
//		syncCardDTO.setPlateNumber("粤B12345");
//		syncCardDTO.setParkCode("tdzntest");
//		syncCardDTO.setEcode("tdzn");
//		syncCardDTO.setDeadlineDate("2017-09-17");
//		syncCardDTO.setStatus(Constants.ENABLE);
//		syncCardDTO.setPrice(110.98);
//		dataItems.add(syncCardDTO);
//		mqttDTO.setCode(Constants.OK);
//		mqttDTO.setServiceId(Constants.CREATE_MONTH_CARD);
//		mqttDTO.setUuid(UuidUtil.getUUID());
//		mqttDTO.setDataItems(dataItems);
//		String sendMessage = JSON.toJSONString(mqttDTO);
//		System.out.println(sendMessage);
		
		// send mqtt message
//		MqttDTO<SendCardRechargeDTO> mqttDTO = new MqttDTO<SendCardRechargeDTO>();
//		List<SendCardRechargeDTO> dataItems = new ArrayList<SendCardRechargeDTO>();
//		SendCardRechargeDTO sendCardRechargeDTO = new SendCardRechargeDTO();
//		sendCardRechargeDTO.setPlateNumber("粤B12345");
//		sendCardRechargeDTO.setRechargeAmount(110.88);
//		sendCardRechargeDTO.setRechargeTime(DateUtils.toString(new Date(), DateUtils.YMDHMS));
//		sendCardRechargeDTO.setParkCode("tdzntest");
//		sendCardRechargeDTO.setPayType(1);
//		sendCardRechargeDTO.setStartDate(DateUtils.toString(new Date(), DateUtils.YMD));
//		sendCardRechargeDTO.setEndDate(DateUtils.toString(new Date(), DateUtils.YMD));
//		sendCardRechargeDTO.setOrderNo(UuidUtil.getYKOrderNo());
//		dataItems.add(sendCardRechargeDTO);
//		mqttDTO.setCode(Constants.OK);
//		mqttDTO.setServiceId(Constants.PAY_MONTH_CARD_ORDER);
//		mqttDTO.setUuid(UuidUtil.getUUID());
//		mqttDTO.setDataItems(dataItems);
//		String sendMessage = JSON.toJSONString(mqttDTO);
//		System.out.println(sendMessage);
		
//		MqttDTO<SyncOrderDTO> mqttDTO = new MqttDTO<SyncOrderDTO>();
//		List<SyncOrderDTO> dataItems = new ArrayList<SyncOrderDTO>();
//		SyncOrderDTO syncOrderDTO = new SyncOrderDTO();
//		syncOrderDTO.setOrderNo(UuidUtil.getTCOrderNo());
//		syncOrderDTO.setPlateNumber("粤B12345");
//		syncOrderDTO.setPayableFee(11.2);
//		syncOrderDTO.setPaidFee(11.0);
//		syncOrderDTO.setDiscountFee(0.2);
//		syncOrderDTO.setPayType(1);
//		syncOrderDTO.setPayTime(new Date());
//		syncOrderDTO.setPayChannel(syncOrderDTO.getPayChannel());
//		syncOrderDTO.setEnterTime(DateUtils.toString(new Date(), DateUtils.YMDHMS));
//		syncOrderDTO.setLeaveTime(DateUtils.toString(new Date(), DateUtils.YMDHMS));
//		syncOrderDTO.setUseTime(11);
//		syncOrderDTO.setParkCode("tdzntest");
//		syncOrderDTO.setType(1);
//		
//		dataItems.add(syncOrderDTO);
//		mqttDTO.setCode(Constants.OK);
//		mqttDTO.setServiceId(Constants.SYNC_PARKING_FEE_ORDER);
//		mqttDTO.setUuid(UuidUtil.getUUID());
//		mqttDTO.setDataItems(dataItems);
//		String sendMessage = JSON.toJSONString(mqttDTO);
//		System.out.println(sendMessage);
	}
}
